package com.zerosky.crm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zerosky.crm.po.Branch;
import com.zerosky.crm.po.Department;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.Pluralize;
import com.zerosky.crm.service.BranchService;
import com.zerosky.crm.service.DepartmentService;
import com.zerosky.crm.service.PluralizeService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.PageInfo;

/**
 * 系统设置（角色、员工） 相关业务
 * 
 * @author
 *
 */
@Controller
public class CompanyController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(CompanyController.class); // 日志

	@Resource(name = "departmentService")
	private DepartmentService departmentService;

	@Resource(name = "branchService")
	private BranchService branchService;

	@Resource(name = "pluralizeService")
	private PluralizeService pluralizeService;

	/**
	 * 去公司jsp页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toCompany.do")
	public String toRoleJsp(HttpServletRequest request, HttpSession session) {
		if (checkPower(session, 74)) {
			return "WEB-INF/jsp/system/companyList";
		} else {
			return "/WEB-INF/jsp/error/404";
		}

	}

	/**
	 * 公司查询 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("queryCompany.do")
	@ResponseBody
	public Map<String, Object> queryCompany(HttpSession session, HttpServletRequest request, Integer limit,
			Integer page, String deptName) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			Map<String, Object> param = new HashMap<String, Object>();
			try {

				param.put("deptName", deptName);
				param.put("limit", limit);
				param.put("page", page);
				PageInfo<Department> pageInfo = departmentService.getDepartmentPageInfoList(param);
				json.put("total", pageInfo.getPageCount());
				// json.put("darw", darw+1);
				json.put("data", pageInfo.getList());
				json.put("code", "1");

			} catch (Exception e) {
				json.put("code", "-1");
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * AJAX 异步 添加
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("addCompany.do")
	@ResponseBody
	public Map<String, Object> addCompany(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Department dept) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			try {
				dept.setDeptId(UUID.randomUUID().toString());
				dept.setCreateDate(new Date());
				dept.setPid("1");
				departmentService.addDepartment(dept);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 根据id查询出分公司信息
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("companyDetail.do")
	@ResponseBody
	public Map<String, Object> companyDetail(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			try {
				json.put("code", 1);
				Department dept = departmentService.getDepartmentById(id);
				json.put("dept", dept);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;

	}

	/**
	 * 编辑分公司
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("editCompany.do")
	@ResponseBody
	public Map<String, Object> editCompany(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, Department dept) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			try {
				departmentService.updateDepartment(dept);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 删除分公司
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping("delCompany.do")
	@ResponseBody
	public Map<String, Object> delCompany(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			String id) {

		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			try {
				departmentService.deleteDepartmentById(id);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/* 对分公司下属部门操作 */
	/**
	 * 去部门jsp页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toBranch.do")
	public String toBranch(HttpServletRequest request, HttpSession session) {
		if (checkPower(session, 75)) {
			List<Department> list = departmentService.getDepartmentList(null);
			request.setAttribute("dept", list);
			return "WEB-INF/jsp/system/branchList";
		} else {
			return "/WEB-INF/jsp/error/404";
		}

	}

	/**
	 * 公司查询 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("queryBranch.do")
	@ResponseBody
	public Map<String, Object> queryBranch(HttpSession session, HttpServletRequest request, Integer limit, Integer page,
			String company, String branchName, String isBranch, String pid) {
		Map<String, Object> json = new HashMap<String, Object>();
			Map<String, Object> param = new HashMap<String, Object>();
			try {
				// if((branchName == "" || branchName == null) && company !=
				// null && company != ""){
				// param.put("queryByCompany", 1);
				// }
				param.put("branchName", branchName);
				param.put("deptId", company);
				param.put("pid", pid);
				param.put("isBranch", isBranch);
				param.put("limit", limit);
				param.put("page", page);
				PageInfo<Branch> pageInfo = branchService.getBranchPageInfoList(param);
				json.put("total", pageInfo.getPageCount());
				// json.put("darw", darw+1);
				json.put("data", pageInfo.getList());
				json.put("code", "1");

			} catch (Exception e) {
				json.put("code", "-1");
				logger.error("获取数据失败，原因：" + e);
			}
		return json;
	}

	/**
	 * AJAX 异步 获取分公司信息
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getCompanyList.do")
	@ResponseBody
	public Map<String, Object> getCompanyList(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 75)) {
			try {
				List<Department> list = departmentService.getDepartmentList(null);
				json.put("deptList", list);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * AJAX 异步 添加
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("addBranch.do")
	@ResponseBody
	public Map<String, Object> addBranch(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Branch branch) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 75)) {
			try {
				branch.setBranchId(UUID.randomUUID().toString());
				branch.setCreateDate(new Date());
				branchService.addBranch(branch);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 根据id查询出部门详细信息
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("branchDetail.do")
	@ResponseBody
	public Map<String, Object> branchDetail(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 75)) {
			try {
				List<Department> list = departmentService.getDepartmentList(null);
				json.put("deptList", list);
				Branch dept = branchService.getBranchById(id);
				json.put("branch", dept);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;

	}

	/**
	 * 编辑信息
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("editBranch.do")
	@ResponseBody
	public Map<String, Object> editBranch(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Branch dept) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 75)) {
			try {
				branchService.updateBranch(dept);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping("delBranch.do")
	@ResponseBody
	public Map<String, Object> delBranch(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 74)) {
			try {
				branchService.deleteBranchById(id);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 去团队jsp页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toTeam.do")
	public String toTeam(HttpServletRequest request, HttpSession session) {
		if (checkPower(session, 76)) {
			List<Department> list = departmentService.getDepartmentList(null);
			request.setAttribute("dept", list);
			return "WEB-INF/jsp/system/teamList";
		} else {
			return "/WEB-INF/jsp/error/404";
		}

	}

	/**
	 * AJAX 异步 获取分公司
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getBranchOffice.do")
	@ResponseBody
	public Map<String, Object> getBranchOffice(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) request.getSession().getAttribute("loginUser");
			Map<String, Object> map = new HashMap<>();
			// 设置权限，如果有权限查看所有销售情况的，则有所有查看权限
			List<Department> list = new ArrayList<Department>();
			map.put("canNotReadAllMessage", false);
			List<Department> listDept = departmentService.getDepartmentList(map);
			if (checkPower(session, 97) || checkPower(session, 98) || checkPower(session, 99)) {

				Department dept = new Department();

				dept.setDeptName("全部分公司");
				dept.setRemake("滨海金控");
				dept.setDeptId("1");
				list.add(dept);
				for (int i = 1; i <= listDept.size(); i++) {
					list.add(listDept.get(i - 1));
				}
			} else if (checkPower(session, 94) || checkPower(session, 95) || checkPower(session, 96)) {
				map.put("employeeId", user.getEmployeeId());
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				if (!user.getQuarters().equals("7") && !user.getQuarters().equals("8")) {
					list.add(user.getDept());
				}
				for (Pluralize pluralize : pluralizeList) {
					for (Department dept : listDept) {
						if (!pluralize.getDeptId().equals(user.getDept().getDeptId())) {
							if (pluralize.getDeptId().equals(dept.getDeptId())) {
								list.add(dept);
							}
						}
					}
				}
				if (list.size() == 0) {
					Department dept2 = new Department();
					dept2.setDeptName("-暂无数据-");
					dept2.setDeptId("99658");
					list.add(dept2);
				}
			}
			json.put("data", list);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取部门
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getDeptFallTeam.do")
	@ResponseBody
	public Map<String, Object> getDeptFallTeam(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id, String pid) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		// Boolean canNotReadAllMessage = !checkPower(session, 44);
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if (id != null && id != "") {
				map.put("deptId", id);
				map.put("isBranch", "isBranch");
			}
			if (pid != null && pid != "") {
				map.put("pid", pid);
			}
			List<Branch> list = new ArrayList<>();
			// if((!canNotReadAllMessage && id!=null && !"".equals(id)) ||
			// user.getBranch() == null ){
			if ((id != null && !"".equals(id)) || user.getBranch() == null) {
				list = branchService.getBranchAllList(map);
			}
			// else if(canNotReadAllMessage && map.size() !=0){
			else if (map.size() != 0) {
				list.add(user.getBranch());
			}
			list = branchService.getBranchAllList(map);
			json.put("branch", list);
			json.put("code", 1);
			// json.put("canNotReadAllMessage", canNotReadAllMessage);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取团队
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getTeamByBranchId.do")
	@ResponseBody
	public Map<String, Object> getTeamByBranchId(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id, String pid) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		Boolean canNotReadAllMessage = false;
		if (!user.getQuarters().equals("0")) {
			canNotReadAllMessage = true;
		}
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if (id != null && id != "") {
				map.put("pid", id);
			} else {
				map.put("pid", "pid");
			}
			List<Branch> list = new ArrayList<>();
			if (canNotReadAllMessage || user.getTeam() == null) {
				list = branchService.getBranchAllList(map);
			} else if (canNotReadAllMessage && user.getTeam() != null && !map.get("pid").equals("pid")) {
				list.add(user.getTeam());
			}

			json.put("branch", list);
			json.put("code", 1);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取分公司
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getDeptOffice.do")
	@ResponseBody
	public Map<String, Object> getDeptOffice(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) request.getSession().getAttribute("loginUser");
			Map<String, Object> map = new HashMap<>();
			// 设置权限，如果有权限查看所有销售情况的，则有所有查看权限
			List<Department> list = new ArrayList<Department>();
			map.put("canNotReadAllMessage", false);
			List<Department> listDept = departmentService.getDepartmentList(map);
			if (checkPower(session, 91) || user.getQuarters().equals("5") || user.getQuarters().equals("6")) {// 有管理员或董事长权限
				map.put("canNotReadAllMessage", false);
				list = departmentService.getDepartmentList(map);
			} else {// 有兼任部门
				map.put("employeeId", user.getEmployeeId());
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				if (!user.getQuarters().equals("7") && !user.getQuarters().equals("8")) {
					list.add(user.getDept());
				}
				for (Pluralize pluralize : pluralizeList) {
					for (Department dept : listDept) {
						if (!pluralize.getDeptId().equals(user.getDept().getDeptId())) {
							if (pluralize.getDeptId().equals(dept.getDeptId())) {
								list.add(dept);
							}
						}
					}
				}
				if (list.size() == 0) {
					Department dept2 = new Department();
					dept2.setDeptName("-暂无数据-");
					dept2.setDeptId("99658");
					list.add(dept2);
				}
			}
			json.put("data", list);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取部门
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getAcquisitionDepartment.do")
	@ResponseBody
	public Map<String, Object> getAcquisitionDepartment(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id, String pid) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		// Boolean canNotReadAllMessage = !checkPower(session, 44);
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if (id != null && id != "") {
				map.put("deptId", id);
				map.put("isBranch", "isBranch");
			}
			if (pid != null && pid != "") {
				map.put("pid", pid);
			}
			List<Branch> list = new ArrayList<Branch>();
			if (user.getQuarters().equals("2")) {// 用户岗位为部门经理，只能看自己部门的
				list.add(user.getBranch());
			} else {
				list = branchService.getBranchAllList(map);
			}
			json.put("branch", list);
			json.put("code", 1);
			// json.put("canNotReadAllMessage", canNotReadAllMessage);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取团队
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getAcquisitionBranch.do")
	@ResponseBody
	public Map<String, Object> getAcquisitionBranch(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id, String pid) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if (id != null && id != "") {
				map.put("pid", id);
			} else {
				map.put("pid", "pid");
			}
			List<Branch> list = new ArrayList<>();
			if (user.getQuarters().equals("1")) {// 用户岗位是团队长。只能看自己团队成员的。
				list.add(user.getTeam());
			} else {
				list = branchService.getBranchAllList(map);
			}

			json.put("branch", list);
			json.put("code", 1);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取分公司
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getDeptAll.do")
	@ResponseBody
	public Map<String, Object> getDeptAll(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			if (checkPower(session, 60) || checkPower(session, 76) || checkPower(session, 75)) {
				Map<String, Object> map = new HashMap<>();
				// 设置权限，如果有权限查看所有销售情况的，则有所有查看权限
				map.put("canNotReadAllMessage", false);
				List<Department> list = departmentService.getDepartmentList(map);
				json.put("data", list);
				json.put("code", 0);
			}else{
				json.put("code", -2);
			}	
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}
}
